<?php

require_once 'core.php';
require_once 'errors.php';

$postdata = json_decode($_POST[action]);

// Action
$action     = $postdata->action;

//print_r($postdata);
// Login Password Batch_Id
$login      = mysql_real_escape_string($postdata->login);
$password   = mysql_real_escape_string(md5($postdata->password));
$batch_id   = mysql_real_escape_string($postdata->batch_id);

// Form_Date To_Date Phone Status Details
$from_date  = mysql_real_escape_string($postdata->from_date);
$to_date    = mysql_real_escape_string($postdata->to_date);
$phone      = mysql_real_escape_string($postdata->phone);
$status     = mysql_real_escape_string($postdata->status);
$details    = mysql_real_escape_string($postdata->details);

switch ($action) {
    case 'cancel':
        if(!empty($login) && !empty($password) && !empty($batch_id)){
            $res_login = mysql_fetch_array(mysql_query("SELECT `id` FROM `users` WHERE `username` = '$login' AND `password` = '$password';"));
            if($res_login[0] != ''){

                $res_batch_id = mysql_fetch_array(mysql_query("SELECT `id` FROM `request` WHERE `id` = '$batch_id';"));

                if($res_batch_id[0] != ''){
                    mysql_query("DELETE    FROM    scheduled_calls
                                 WHERE     scheduled_calls.request_detail_id IN (
                                                SELECT  request_details.id
                                                FROM     request_details
                                                WHERE   request_details.request_id = $batch_id)");

                    mysql_query("UPDATE request
                                SET     request.`status` = 5
                                WHERE   request.id = $batch_id");

                    mysql_query("UPDATE request_details
                                SET     request_details.`status` = 7
                                WHERE   request_details.request_id = $batch_id");

                    $error = '0';

                    $getresult = new getError($error, $batch_id);

                }else{
                    $error = '2';
                }

            }else{
                $error = '36';
            }
        }else{
            $error = '0';
        }
    break;
    case 'phones_report':
        if(!empty($login) && !empty($password)){
            $res = mysql_fetch_array(mysql_query("SELECT `id` FROM `users` WHERE `username` = '$login' AND `password` = '$password';"));
            if($res[0] != ''){
                $wh = "";
                if (!empty($from_date) && !empty($to_date)) {
                    $wh.="AND (request.start_datetime BETWEEN '$from_date' AND '$to_date')";
                }else
                if (!empty($from_date)) {
                    $from_date=date("Y-m-d H:i:s", strtotime("$to_date - 4 hours"));
                    $wh.="AND (request.start_datetime BETWEEN '$from_date' AND '$to_date')";
                }else
                if ( !empty($to_date)) {
                    $to_date=date("Y-m-d H:i:s", strtotime("now - 4 hours"));
                    $wh.="AND (request.start_datetime BETWEEN '$from_date' AND '$to_date')";
                }
                if (!empty($phone))  {
                    $wh.=" AND `request_details`.`phone_number`='$phone'";
                };

                if (!empty($batch_id)) {
                    $wh.=" AND `request`.`id` = '$batch_id'";
                };

                if (!empty($status)){
                    $wh.=" AND `request_details`.`status` = '$status'";
                };

                if ($wh !="")    {
                    $where="where TRUE  $wh";
                };

                $error = '0';
              $res_report = mysql_query("SELECT results.call_id, 
                    							results.batch_id, 
                    							results.phone, 
                    							results.start_date, 
                    							results.retries, 
                    							SUM(results.listen_time) AS listen_time, 
                    							results.originator, 
                    							results.answer_time, 
                    							results.duration,
                                                results.`status`

                                        FROM    (SELECT `request_details`.`id` AS `call_id`,
                        								`request`.`id` AS `batch_id`,
                        								`request_details`.`phone_number` AS `phone`,
                        								`request`.`start_datetime` AS `start_date`,
                        								`request_details`.`retries`,
                        								IF(ISNULL(`calls`.`duration`), 0, `calls`.`duration`) AS `listen_time`,
                        								IF(ISNULL(`calls`.`source`), 0, `calls`.`source`)  AS `originator`,
                        				                IF(ISNULL(FROM_UNIXTIME(`calls`.`call_datetime` + calls.wait_time)), '0000-00-00 00:00:00', FROM_UNIXTIME(`calls`.`call_datetime` + calls.wait_time)) AS `answer_time`,
                        								IF(ISNULL(`calls`.`duration`), 0 , `calls`.`duration`) AS duration,
                                                        request_details_status.`name` AS `status`
                                        FROM 			`request`
                                        JOIN 			`request_details` ON `request`.`id` = request_details.request_id
                                        LEFT JOIN 		`calls` ON `request_details`.`id` = calls.request_details_id
                                        JOIN            request_details_status ON request_details.`status` = request_details_status.id
                                        $where
                                        ORDER BY calls.id DESC) AS results
        
                                        GROUP BY results.call_id");

                while ($row_report = mysql_fetch_assoc($res_report)) {
                    if ($details==1){
                          $res_report1=mysql_query("SELECT   calls.id AS try_id,
                                                			 FROM_UNIXTIME(calls.call_datetime) AS queue_d,
                                                			 FROM_UNIXTIME(calls.call_datetime) AS start_d,
                                                			 FROM_UNIXTIME(calls.call_datetime + calls.wait_time) AS answer_d,
                                                			 FROM_UNIXTIME(calls.call_datetime + calls.wait_time + calls.duration) AS end_d,
                                                			 (calls.duration + calls.wait_time) AS duration,
                                                			 (calls.duration) AS answer_time,
                                                			 CASE WHEN  calls.`status` = 'NO ANSWER' THEN 'NOANSWER'
                												  WHEN  calls.`status` = 'ANSWERED' THEN 'ANSWER'
                												  WHEN  calls.`status` = 'BUSY' THEN 'BUSY'
                                                                  WHEN  calls.`status` = 'FULL' THEN 'ANSWER'
                                                                  WHEN  calls.`status` = 'FAILED' THEN 'CABORT'
                								             END AS dial_status,
                                                             IF(calls.`status` = 'FULL', 1, IF(calls.duration >= request.done_listen_time, 1, 0)) AS script_done
                                                    FROM    calls
                                                    JOIN    request_details ON request_details.id = calls.request_details_id
                                                    JOIN    request ON request.id = request_details.request_id
                                                    WHERE   calls.request_details_id='$row_report[call_id]'");
                                        while ($row_report1 = mysql_fetch_assoc($res_report1)) {
                                            $row_report['try'][]=$row_report1;
                                        }
                    }

                    $json[] = $row_report;


                }




            }else{
                $error = '36';
            }
        }else{
            $error = '0';
        }
    break;
    default:
        $error = '28';
}
$getresult = new getError($error, $batch_id);
$arr=json_decode($getresult->getJson(),true);
$arr[call] =$json;
echo json_encode($arr);


?>